package com.faxsun.web.processor;

import org.broadleafcommerce.common.web.BroadleafRequestContext;
import org.broadleafcommerce.core.search.domain.ProductSearchCriteria;
import org.broadleafcommerce.core.web.processor.PaginationSizeLinkProcessor;
import org.broadleafcommerce.core.web.util.ProcessorUtils;
import org.thymeleaf.Arguments;
import org.thymeleaf.dom.Element;
import org.thymeleaf.standard.expression.Expression;
import org.thymeleaf.standard.expression.StandardExpressions;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Rongxin on 2015-08-11.
 */
public class FSPaginationSizeLinkProcessor extends PaginationSizeLinkProcessor {

    @Override
    protected Map<String, String> getModifiedAttributeValues(Arguments arguments, Element element, String attributeName) {

        Map<String, String> attributes = new HashMap<String, String>();

        HttpServletRequest request = BroadleafRequestContext.getBroadleafRequestContext().getRequest();
        String baseUrl = request.getRequestURL().toString();
        Map<String, String[]> params = new HashMap<String, String[]>(request.getParameterMap());

        Expression expression = (Expression) StandardExpressions.getExpressionParser(arguments.getConfiguration())
            .parseExpression(arguments.getConfiguration(), arguments, element.getAttributeValue(attributeName));
        Integer pageSize = (Integer) expression.execute(arguments.getConfiguration(), arguments);

        if (pageSize != null && pageSize > 1) {
            params.put(ProductSearchCriteria.PAGE_SIZE_STRING, new String[]{pageSize.toString()});
        } else {
            params.remove(ProductSearchCriteria.PAGE_SIZE_STRING);
        }

        if (params.containsKey(ProductSearchCriteria.PAGE_NUMBER)) {
            params.remove(ProductSearchCriteria.PAGE_NUMBER);
        }

        String url = ProcessorUtils.getUrl(baseUrl, params);
        attributes.put("href", url);

        return attributes;
    }
}
